package com.jp.knowledge.activity;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.google.gson.JsonObject;
import com.jiayen.cache.FileCacheManager;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.adapter.AlbumImgAdapter;
import com.jp.knowledge.adapter.OnItemListerner;
import com.jp.knowledge.adapter.VipZoneAdapter;
import com.jp.knowledge.adapter.daily_knowledge.DailyKnowledgePackageAdapter;
import com.jp.knowledge.broad.LocalBroadCast;
import com.jp.knowledge.comm.SlidingActivity;
import com.jp.knowledge.command.Command;
import com.jp.knowledge.command.CommandInvoker;
import com.jp.knowledge.command.CommandReceiver;
import com.jp.knowledge.dialog.CommDialog;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.DailyKnowledgePackageModel;
import com.jp.knowledge.model.HeadLineData;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.InfoData;
import com.jp.knowledge.model.KnowlageListModel;
import com.jp.knowledge.model.KnowlageModel;
import com.jp.knowledge.model.ProductUIModel;
import com.jp.knowledge.model.UserData;
import com.jp.knowledge.my.activity.IntegralBuyActivity;
import com.jp.knowledge.my.adapter.UiFragmentAdapter;
import com.jp.knowledge.my.base.RecycleVAdapter;
import com.jp.knowledge.refresh.JpRefreshView;
import com.jp.knowledge.util.ImageLoadUtil;
import com.jp.knowledge.util.ResultSubscriber;
import com.jp.knowledge.util.ShareBuilder;
import com.umeng.socialize.media.UMImage;

import org.xutils.common.util.DensityUtil;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


public class KnowlageDetailActivity extends SlidingActivity implements ResultSubscriber.OnResultListener, View.OnClickListener, CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener {

    private static final int GET_LIST_CODE = 0x01;
    private static final int COLLECTION_CODE = 0x02;
    private static final int ITEM_COLLECTION_CODE = 0x03;
    private static final int PAY_CODE = 0x04;

    @ViewInject(R.id.refresh)
    protected CanRefreshLayout mRefresh;
    @ViewInject(R.id.content_rv)
    private RecyclerView listView;
    @ViewInject(R.id.can_refresh_footer)
    private JpRefreshView footer;
    @ViewInject(R.id.permissionView)
    private LinearLayout emptyLayout;
    @ViewInject(R.id.image_cover)
    private ImageView imageCover;

    private String id;
    private String cataId;
    private String packageId;
    private HeadLineData extra;
    private int showType;
    private KnowlageModel knowlageModel;
    private VipZoneAdapter linearAdpter;
    private DailyKnowledgePackageAdapter knowledgeAdapter;
    private LinearLayoutManager linearLayoutManager;
    private AlbumImgAdapter staggeredAdapter;
    private StaggeredGridLayoutManager staggeredGridLayoutManager;
    private List<DailyKnowledgePackageModel.ListBean> uiModels;

    private PopupWindow moreBtnPopupWindow;
    private View popWindowView;
    private TextView showImgBtn;
    private TextView collectionBtn;
    private TextView shareBtn;
    private TextView downloadBtn;
    private View showImgSpliteLine;
    private View downloadSplitLine;

    private ShareBuilder shareBuilder;
    private String cachePath;
    private FileCacheManager fileCacheManager;
    private LocalBroadcastManager localBroadcastManager;
    private LocalBroadCast localBroadCast;

    private CommDialog payDialog;

    @Override
    protected int getResourceId() {
        return R.layout.activity_knowlage_detail;
    }

    @Override
    protected void init() {
        contentView.setBackgroundResource(R.color.gray_bg);
        initData();
        initCache();
        initBroadcast();
        initView();
        initPopupWindows();
        updateView(knowlageModel);
        emptyLayout.setVisibility(View.GONE);
        readCache();
    }

    @Override
    protected void onDestroy() {
        localBroadcastManager.unregisterReceiver(localBroadCast);
        saveDataToCache(knowlageModel);
        super.onDestroy();
    }

    private void initData(){
        Intent intent = getIntent();
        id  = intent.getStringExtra("id");
        cataId  = intent.getStringExtra("cataId");
        packageId  = intent.getStringExtra("packageId");
        showType = intent.getIntExtra("showType", 0);
        try {
            Bundle bundle = intent.getBundleExtra("extra");
            extra = (HeadLineData) bundle.getSerializable("data");
        } catch (Exception e){
            extra = null;
        }

        uiModels = new ArrayList<>();
    }

    private void initCache(){
        cachePath = getCacheDir().getPath() + "/knowlageDetail_" + id + "_" + cataId + "_" + packageId + ".dat";
        fileCacheManager = new FileCacheManager();
    }

    private void initBroadcast() {
        localBroadcastManager = LocalBroadcastManager.getInstance(mContext);
        localBroadCast = new LocalBroadCast(new LocalBroadCast.BroadCastCallBack() {
            @Override
            public void done(Context context, Intent intent) {
                String action = intent.getAction();
                if(LocalBroadCast.DETAIL_SC_BROAD.equals(action)) {
                    for (DailyKnowledgePackageModel.ListBean uiModel : uiModels)
                        if (uiModel.getId().equals(intent.getStringExtra("id"))) {
                            uiModel.setIsFollow(intent.getIntExtra("isCollection", 0));
                            staggeredAdapter.updateAdapter(uiModels);
                            return;
                        }
                } else if(LocalBroadCast.COMM_CHANGE_SIZE.equals(action)){
                    linearAdpter.changeTextSize();
                }
            }
        });
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(LocalBroadCast.DETAIL_SC_BROAD);
        intentFilter.addAction(LocalBroadCast.COMM_CHANGE_SIZE);
        localBroadcastManager.registerReceiver(localBroadCast, intentFilter);;
    }

    private void initView() {
        String title=getIntent().getStringExtra("title");
        topName.setText(title);
        leftIcon.setImageResource(R.mipmap.guanzhufanhui);
        rightIcon.setImageResource(R.mipmap.guanzhugengduo);
        rightIcon.setVisibility(View.VISIBLE);
        leftIcon.setOnClickListener(this);
        rightIcon.setOnClickListener(this);

        imageCover.getLayoutParams().height = (int) (DensityUtil.getScreenWidth() * 302f / 922f + 0.5f);

        ((TextView)emptyLayout.findViewById(R.id.remind_text)).setText("暂无数据~");
        emptyLayout.findViewById(R.id.remind_btn).setVisibility(View.GONE);

        mRefresh.setTag(1);
        mRefresh.setOnRefreshListener(this);
        mRefresh.setLoadMoreEnabled(true);
        mRefresh.setOnLoadMoreListener(this);
        mRefresh.setLoadMoreEnabled(showType != 1);

        listView.setHasFixedSize(true);
        linearAdpter = new VipZoneAdapter(mContext, null);
        knowledgeAdapter = new DailyKnowledgePackageAdapter(mContext, null);
        linearLayoutManager = new LinearLayoutManager(mContext){
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        linearAdpter.setOnItemListener(new OnItemListerner() {
            @Override
            public void onItemClick(View view, int position) {
                onLinearItemClick(position);
            }
        });

        staggeredAdapter = new AlbumImgAdapter(mContext, null);
        staggeredGridLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL){
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        staggeredAdapter.addItemClickListener(new RecycleVAdapter.OnItemClickListener() {
            @Override
            public void itemSelect(int position) {
                onStaggeredItemClick(position);
            }
        });
        staggeredAdapter.setItemCollectionListener(new AlbumImgAdapter.ItemCollectionListener() {
            @Override
            public void onItemCollectionClick(int position) {
                KnowlageDetailActivity.this.onItemCollectionClick(position);
            }
        });
    }

    private void initPopupWindows(){
        popWindowView = View.inflate(mContext, R.layout.poput_more, null);
        showImgBtn = (TextView) popWindowView.findViewById(R.id.pop_showImg);
        collectionBtn = (TextView) popWindowView.findViewById(R.id.pop_collection);
        shareBtn = (TextView) popWindowView.findViewById(R.id.pop_share);
        downloadBtn = (TextView) popWindowView.findViewById(R.id.pop_download);
        showImgSpliteLine = popWindowView.findViewById(R.id.line1);
        downloadSplitLine = popWindowView.findViewById(R.id.line3);
        showImgBtn.setTag(false);
        showImgBtn.setOnClickListener(this);
        collectionBtn.setOnClickListener(this);
        shareBtn.setOnClickListener(this);
        downloadBtn.setOnClickListener(this);
        showImgBtn.setTag(false);
        collectionBtn.setTag(false);
        if(extra != null && extra.getDownloadUrl() != null){
            downloadBtn.setVisibility(View.VISIBLE);
            downloadSplitLine.setVisibility(View.VISIBLE);
        } else{
            downloadBtn.setVisibility(View.GONE);
            downloadSplitLine.setVisibility(View.GONE);
        }

        moreBtnPopupWindow = new PopupWindow(popWindowView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        moreBtnPopupWindow.setOutsideTouchable(true);
        moreBtnPopupWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));
        popWindowView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                popWindowView.getViewTreeObserver().removeOnPreDrawListener(this);
                moreBtnPopupWindow.dismiss();
                moreBtnPopupWindow.showAsDropDown(rightIcon,
                        -popWindowView.getMeasuredWidth()+rightIcon.getWidth(), 0);
                return false;
            }
        });

        payDialog = new CommDialog(mContext);
        payDialog.setTag(false);
        payDialog.setRightListener(this);
    }

    @Override
    public void onClick(View v) {
        if(v == leftIcon){
            this.finish();
        } else if(v == rightIcon){
            popWindowView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
            moreBtnPopupWindow.showAsDropDown(rightIcon,
                    -popWindowView.getMeasuredWidth()+rightIcon.getWidth(), 0);
        } else if(v == showImgBtn){
            moreBtnPopupWindow.dismiss();
            showImgBtn.setTag(!(boolean) showImgBtn.getTag());
            updateShowImgBtn();
            mRefresh.autoRefresh();
        } else if(v == collectionBtn){
            moreBtnPopupWindow.dismiss();
            collectionBtn.setTag(!(boolean)collectionBtn.getTag());
            JsonObject param = new JsonObject();
            param.addProperty("id", packageId);
            param.addProperty("type", 26);
            if((boolean)collectionBtn.getTag())
                HttpHelper.getInstance(mContext).collectionHead(param, COLLECTION_CODE, this);
            else
                HttpHelper.getInstance(mContext).unCollection(param, COLLECTION_CODE, this);
            updateCollectionBtn();
        } else if(v == shareBtn){
            moreBtnPopupWindow.dismiss();
            if(shareBuilder == null){
                shareBuilder = new ShareBuilder(this)
                        .withTitle(mContext.getResources().getString(R.string.app_name));
            }
            shareBuilder.withText(knowlageModel.getTitle())
                    .withCopyContent(knowlageModel.getTitle() + " " + knowlageModel.getShareUrl())
                    .withTargetUrl(knowlageModel.getShareUrl())
                    .withQRCodeUrl(knowlageModel.getShareUrl());
            try{
                shareBuilder.withMedia(new UMImage(mContext, knowlageModel.getCover()));
            } catch (Exception e){
                shareBuilder.withMedia(new UMImage(mContext, R.mipmap.icon_launcher));
            } finally {
                shareBuilder.build().open();
            }
        } else if(v == downloadBtn){
            moreBtnPopupWindow.dismiss();
            toDownload();
        } else if(v.getId() == R.id.right_btn){
            if(knowlageModel == null)
                return;
            if((boolean) payDialog.getTag()){
                JsonObject param = new JsonObject();
                param.addProperty("type", knowlageModel.getType());
                param.addProperty("id", packageId);
                param.addProperty("integral", knowlageModel.getIntegral());
                HttpHelper.getInstance(mContext).integralPurchase(param, PAY_CODE, this);
            } else{
                startActivity(new Intent(mContext, IntegralBuyActivity.class));
            }
        }
    }

    private void onLinearItemClick(int position){
        KnowlageListModel data = knowlageModel.getList().get(position);
        if(data.getLayout() == 5){
            Intent intent = new Intent(mContext, KnowlageDetailActivity.class);
            intent.putExtra("cataId", data.getId());
            intent.putExtra("packageId", data.getPackageId());
            intent.putExtra("title", data.getTitle());
            startActivity(intent);
        } else {
//            Intent intent = new Intent(mContext, InfoDataDetailActivity.class);
//            intent.putExtra("id", data.getId());
//            intent.putExtra("type", data.getType());
//            intent.putExtra("linkTitle", data.getTitle());
//            try {
//                intent.putExtra("linkIcon", data.getImglist().get(0).getSrc());
//            }catch (Exception e){} finally {
//                startActivity(intent);
//            }

            CommandReceiver commandReceiver = new CommandReceiver.Builder(mContext)
                    .withCompanyId(data.getCompanyId())
                    .withRecordId(data.getRecordId())
                    .withParameterId(data.getType()+"")
                    .build();
            Command commandObject = Command.create(data.getCommand(), commandReceiver);
            CommandInvoker.executeCommand(commandObject);
        }
    }

    private void onStaggeredItemClick(int position){
        if(uiModels.get(position).getLayout() == 5){
            DailyKnowledgePackageModel.ListBean data = uiModels.get(position);
            Intent intent = new Intent(mContext, KnowlageDetailActivity.class);
            intent.putExtra("cataId", data.getId());
            intent.putExtra("packageId", data.getPackageId());
            intent.putExtra("title", data.getTitle());
            startActivity(intent);
        } else {
            List<ProductUIModel> datas = new ArrayList<>();
            int index = 0;
            for(int i = 0; i < uiModels.size(); i++){
                DailyKnowledgePackageModel.ListBean model = uiModels.get(i);
                if(model.getLayout() == 5)
                    continue;
                else if(i == position)
                    index = datas.size();
                ProductUIModel uiModel = new ProductUIModel();
                uiModel.setProductId(model.getProductId());
                uiModel.setId(model.getId());
                uiModel.setName(model.getName());
                uiModel.setProductName(model.getName());
                uiModel.setCover(model.getCover());
                uiModel.setIsFollow(model.getIsFollow());
                uiModel.setType(model.getType());
                datas.add(uiModel);
            }
            ImageActivity.startActivity(mContext, index, 1, datas);
        }
    }

    private void onItemCollectionClick(int position){
        DailyKnowledgePackageModel.ListBean data = uiModels.get(position);
        JsonObject param = new JsonObject();
        param.addProperty("token", HttpHelper.token);
        param.addProperty("id", data.getId());
        param.addProperty("type", 15);
        if(data.getIsFollow() == 1)
            HttpHelper.getInstance(mContext).unCollection(param, position * 10 + ITEM_COLLECTION_CODE, this);
        else
            HttpHelper.getInstance(mContext).collectionHead(param, position * 10 + ITEM_COLLECTION_CODE, this);
        data.setIsFollow(data.getIsFollow()==1 ? 0 : 1);
        listView.getAdapter().notifyDataSetChanged();
    }

    @Override
    public void onRefresh() {
        mRefresh.setTag(1);
        getData();
    }

    @Override
    public void onLoadMore() {
        if(footer.isLoadComplete()) {
            onCompleted(GET_LIST_CODE);
        } else {
            mRefresh.setTag((int) mRefresh.getTag() + 1);
            getData();
        }
    }

    private void getData() {
        JsonObject param = new JsonObject();
        param.addProperty("mainId", id);
        param.addProperty("cataId", cataId);
        param.addProperty("packageId", packageId);
        param.addProperty("page", (int)mRefresh.getTag());
        param.addProperty("showType", showType);
        if((boolean)showImgBtn.getTag())
            param.addProperty("type", 15);
        HttpHelper.getInstance(mContext).knowledgePackage(param, GET_LIST_CODE, this);
    }

    private void readCache(){
        Observable.create(new Observable.OnSubscribe<KnowlageModel>() {
            @Override
            public void call(Subscriber<? super KnowlageModel> subscriber) {
                KnowlageModel data = (KnowlageModel) fileCacheManager.readObject(cachePath);
                subscriber.onNext(data);
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Observer<KnowlageModel>() {
            @Override
            public void onCompleted() {
                if(knowlageModel == null || knowlageModel.getList() == null ||  knowlageModel.getList().size() == 0){
                    mRefresh.autoRefresh();
                } else {
                    mRefresh.setTag(1);
                    getData();
                }
            }
            @Override
            public void onError(Throwable e) {
                onCompleted();
            }
            @Override
            public void onNext(KnowlageModel data) {
                knowlageModel = data;
                if(knowlageModel != null) {
                    showImgBtn.setTag(knowlageModel.getType() != 0);
                    collectionBtn.setTag(knowlageModel.getIsFollow() == 1);
                }
                updateView(knowlageModel);
                emptyLayout.setVisibility(View.GONE);
            }
        });
    }

    private void saveDataToCache(final KnowlageModel knowlageModel){
        new Thread(new Runnable() {
            @Override
            public void run() {
                if(knowlageModel != null) {
                    if (listView.getLayoutManager() instanceof LinearLayoutManager)
                        knowlageModel.setType(0);
                    else
                        knowlageModel.setType(15);
                }
                fileCacheManager.wirteObject(knowlageModel, cachePath);
            }
        }).start();
    }

    @Override
    public void onStart(int requestType) {}
    @Override
    public void onCompleted(int requestType) {
        if(requestType == GET_LIST_CODE) {
            if((int)mRefresh.getTag() == 1)
                mRefresh.refreshComplete();
            else
                mRefresh.loadMoreComplete();
        }
    }
    @Override
    public void onError(int requestType) {
        if(requestType == COLLECTION_CODE){
            collectionBtn.setTag(!(boolean)collectionBtn.getTag());
            updateCollectionBtn();
        } else if(requestType%10 == ITEM_COLLECTION_CODE){
            KnowlageListModel data = knowlageModel.getList().get(requestType/10);
            data.setIsFollow(data.getIsFollow()==1 ? 0 : 1);
            listView.getAdapter().notifyDataSetChanged();
        }
        onCompleted(requestType);
    }
    @Override
    public void onNext(IModel data, int requestType) {
        if(data.getErrcode() != 0){
            ToasUtil.toast(mContext, data.getMessage());
            onError(requestType);
        } else if(requestType == GET_LIST_CODE) {
            KnowlageModel tmpData = data.getEntity(KnowlageModel.class);
            if((int)mRefresh.getTag() == 1 || knowlageModel == null)
                knowlageModel = tmpData;
            else if(knowlageModel.getList() == null && tmpData != null)
                knowlageModel.setList(tmpData.getList());
            else if(tmpData != null && tmpData.getList() != null && tmpData.getList().size() > 0)
                knowlageModel.getList().addAll(tmpData.getList());
            if((int)mRefresh.getTag() != 1 && (tmpData == null || tmpData.getList() == null || tmpData.getList().size() == 0))
                footer.setLoadComplete(true);
            else
                footer.setLoadComplete(false);
            updateView(knowlageModel);
        } else if(requestType == COLLECTION_CODE){
            LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(LocalBroadCast.DETAIL_SC_BROAD)
                    .putExtra("id", packageId)
                    .putExtra("isCollection", (boolean)collectionBtn.getTag() ? 1 : 0));
        } else if(requestType%10 == ITEM_COLLECTION_CODE){

        } else if(requestType == PAY_CODE){
            knowlageModel.setViewPermit(0);
            toDownload();
            onRefresh();
        }
    }

    private void updateView(KnowlageModel knowlageModel){
        if(knowlageModel == null){
            emptyLayout.setVisibility(View.VISIBLE);
            shareBtn.setVisibility(View.GONE);
            imageCover.setVisibility(View.GONE);
            return;
        } else{
            shareBtn.setVisibility(View.VISIBLE);

            if(!TextUtils.isEmpty(knowlageModel.getDownloadUrl())){
                downloadBtn.setVisibility(View.VISIBLE);
                downloadSplitLine.setVisibility(View.VISIBLE);
            } else{
                downloadBtn.setVisibility(View.GONE);
                downloadSplitLine.setVisibility(View.GONE);
            }
        }
        showType = knowlageModel.getShowType();

        showImgBtn.setVisibility(showType == 1 ? View.GONE : View.VISIBLE);
        showImgSpliteLine.setVisibility(showType == 1 ? View.GONE : View.VISIBLE);

        if(showType == 1 && !(boolean)showImgBtn.getTag()){
            imageCover.setVisibility(View.VISIBLE);
            ImageLoadUtil.load(mContext, knowlageModel.getCover(), imageCover);
        } else{
            imageCover.setVisibility(View.GONE);
        }
        List<DailyKnowledgePackageModel> datas = knowlageModel.getList();
        if(datas == null || datas.size() == 0)
            emptyLayout.setVisibility(View.VISIBLE);
        else
            emptyLayout.setVisibility(View.GONE);
        if(!TextUtils.isEmpty(knowlageModel.getTitle()))
            topName.setText(knowlageModel.getTitle());
        if(!(boolean)showImgBtn.getTag()){
            if(listView.getLayoutManager() != linearLayoutManager)
                listView.setLayoutManager(linearLayoutManager);
            if(showType == 1 && listView.getAdapter() != knowledgeAdapter)
                listView.setAdapter(knowledgeAdapter);
            else if(showType != 1 && listView.getAdapter() != linearAdpter)
                listView.setAdapter(linearAdpter);
            if(showType == 1) {
                knowledgeAdapter.updateAdapter(datas);
            } else {
                linearAdpter.updataAdapter(datas);
            }
        } else{
            if(listView.getLayoutManager() != staggeredGridLayoutManager)
                listView.setLayoutManager(staggeredGridLayoutManager);
            if(listView.getAdapter() != staggeredAdapter)
                listView.setAdapter(staggeredAdapter);
            uiModels.clear();
            if(datas != null) {
                for (DailyKnowledgePackageModel model : datas) {
                    if (model == null)
                        continue;
                    if(model.getLayout() == 5){
                        DailyKnowledgePackageModel.ListBean data = new DailyKnowledgePackageModel.ListBean();
                        data.setPackageId(model.getPackageId());
                        data.setLayout(model.getLayout());
                        data.setId(model.getId());
                        data.setName(model.getTitle());
                        uiModels.add(data);
                    } else if(model.getList() != null && model.getList().size() > 0) {
                        uiModels.addAll(model.getList());
                    }
                }
            }
            staggeredAdapter.updateAdapter(uiModels);
        }
        updateShowImgBtn();
        updateCollectionBtn();
    }

    private void updateShowImgBtn(){
        boolean showImg = (boolean)showImgBtn.getTag();
        showImgBtn.setText(showImg ? "显示全部" : "只显示图片");
    }

    private void updateCollectionBtn(){
        boolean isCollection = (boolean)collectionBtn.getTag();
        collectionBtn.setText(isCollection ? "取消收藏" : "收藏");
    }

    private void toDownload(){
//        if(extra == null)
//            return;
//        String url = extra.getDownloadUrl();
//        String title = extra.getFileName();
//        String img;
//        try{
//            img = extra.getImglist().get(0).getSrc();
//        } catch (Exception e){
//            img = null;
//        }
        if(knowlageModel == null)
            return;
        if(knowlageModel.getViewPermit() == 8){
            UserData userData = application.getUserData();
            if(userData != null) {
                if (userData.getIntegralNum() >= knowlageModel.getIntegral()) {
                    payDialog.setTag(true);
                    payDialog.setContent("是否确定支付" + knowlageModel.getIntegral() + "知识币下载内容？");
                } else {
                    payDialog.setTag(false);
                    payDialog.setContent("你当前知识币不足，是否充值知识币？");
                }
                payDialog.show();
            }
            return;
        }
        String url = knowlageModel.getDownloadUrl();
        String title = knowlageModel.getFileName();
        String img = knowlageModel.getCover();
        String remind;
        double fileSize = extra.getFileSize();
        if(fileSize < 1024)
            remind = String.format(Locale.getDefault(), "扫我即可下载(%.2fB)", fileSize);
        else if(fileSize < 1024 * 1024)
            remind = String.format(Locale.getDefault(), "扫我即可下载(%.2fk)", fileSize / 1024);
        else if(fileSize < 1024 * 1024 * 1024)
            remind = String.format(Locale.getDefault(), "扫我即可下载(%.2fM)", fileSize / 1024 / 1024);
        else
            remind = String.format(Locale.getDefault(), "扫我即可下载(%.2fG)", fileSize / 1024 / 1024 / 1024);
        QrCodeShowActivity.openQRCode(mContext, url, title, url, img, remind);
    }
}
